<template>
  <div id="app">
    <div class="imui-center">
      <lemon-imui
        ref="IMUI"
        :user="user"
        width="100%"
        height="700px"
        :hide-menu="hideMenu"
        :contextmenu="contextmenu"
        :hide-menu-avatar="hideMenuAvatar"
        :hide-message-name="hideMessageName"
        :hide-message-time="hideMessageTime"
        @change-contact="handleChangeContact"
        @pull-messages="handlePullMessages"
        @message-click="handleMessageClick"
        @send="handleSend"
      />
      <!-- 预览接口 -->
      <el-image-viewer
        v-if="drawer"
        :on-close="handleImageClose"
        :url-list=" previewUrl"
        :z-index = 9999
      />
    </div>
  </div>
</template>
<script>
import { h } from 'vue'
import EmojiData from '../assets/emoji/emoji'
import {
  addMessage,
  getContact,
  getMessages,
  updateMessageByMessageID,
  updateMessagesCheck,
  uploadFile
} from '../api/websocket'
import store from '../store'
import { getChineseHeadLetter } from '../utils/zh-string-util'

export default {
  name: 'LemonIM',
  components: { 'el-image-viewer': () => import('element-ui/packages/image/src/image-viewer') },
  data() {
    return {
      theme: 'default',
      uploadURL: '',
      hideMenuAvatar: false,
      hideMenu: false,
      hideMessageName: false,
      hideMessageTime: false,
      totalUnread: 0,
      drawer: false,
      previewUrl: [],
      contactList: [{

      }],
      unreadData: [{

      }],
      contextmenu: [
        {
          visible: instance => {
            return instance.message.type === 'text'
          },
          text: '复制文字',
          click: (e, instance, hide) => {
            this.$clipboard(instance.message.content);
            this.$message({
              type: 'success',
              message: '复制成功!'
            })
            hide()
          }
        },
        {
          visible: instance => {
            return instance.message.type === 'image'
          },
          text: '下载图片',
          click: (e, instance, hide) => {
            const { message } = instance
            this.download(message.content, message.fileName, message.type)
            hide()
          }
        },
        {
          visible: instance => {
            return instance.message.type === 'file'
          },
          text: '下载文件',
          click: (e, instance, hide) => {
            const { message } = instance
            this.download(message.content, message.fileName, message.type)
            hide()
          }
        }
      ],
      currentContactId: -1,
      pageNumber: 1,
      pageSize: 15,
      user: {
        id: '1',
        displayName: 'June',
        avatar: ''
      },
      audio: new Audio(require('../../static/audio/notification.mp3'))
    }
  },
  computed: {
    getWsMsg() {
      return this.$store.getters.webSocketMsg
    }
  },
  watch: {
    getWsMsg: {
      handler: function(newVal) {
        this.getMessage(newVal)
      }
    }
  },
  destroyed() {
    this.$store.dispatch('setCurrentContractId', '')
  },
  created() {
  },
  mounted() {
    const { IMUI } = this.$refs
    IMUI.clearMessages()
    IMUI.initEditorTools([
      {
        name: 'emoji'
      },
      {
        name: 'uploadFile'
      },
      {
        name: 'uploadImage'
      }
    ])
    IMUI.initMenus([
      {
        name: 'messages',
        unread: 0
      },
      {
        name: 'contacts'
      }
    ])
    IMUI.initEmoji(EmojiData)
    const userInfo = JSON.parse(localStorage.getItem('userInfo'))
    this.user.displayName = userInfo.nickName
    this.user.avatar = userInfo.avatar
    this.user.id = userInfo.id
    this.uploadURL = store.state.baseURL + 'upload'
    getContact(this.user.id).then((res) => {
      this.contactList = res
      for (let i = 0; i < this.contactList.length; i++) {
        this.contactList[i].index = getChineseHeadLetter(this.contactList[i].displayName)
        if(this.contactList[i].lastContent !== undefined && this.contactList[i].lastContent !== null) {
          this.contactList[i].lastContent = IMUI.lastContentRender({
            type: this.contactList[i].type,
            content: this.contactList[i].lastContent
          })
        }
      }
      IMUI.initContacts(this.contactList)
    })
  },
  methods: {
    getMessage: function(event) {
      // this.taleList.push(JSON.parse(event.data))
      const { IMUI } = this.$refs
      const contacts = this.contactList
      let is_exist_contact = false
      const res = JSON.parse(event)
      res.toContactId = res.fromUser.id
      if (res.fromUser.id === store.getters.currentContractId) {
        this.audio.play()
        if(res.fromUser.id !== '4'){
          updateMessageByMessageID(res.id)
        }
      }
      for (let i = 0; i < contacts.length; i++) {
        if (contacts[i].id === res.toContactId) {
          is_exist_contact = true
          break
        }
      }
      if (is_exist_contact) {
        IMUI.appendMessage(res, true)
        IMUI.messageViewToBottom()
      } else {
        const contract = {
          id: res.fromUser.id,
          displayName: res.fromUser.displayName,
          avatar: res.fromUser.avatar,
          unread: 1,
          lastContent: res.content,
          lastSendTime: res.sendTime
        }
        this.contactList.push(contract)
        IMUI.appendContact(contract)
      }
    },
    handleMessageClick(e, key, message, instance) {
      var imageTypes = ['image']
      if (imageTypes.includes(message.type)) {
        this.previewUrl.push(message.content)
        this.drawer = true
      }
    },
    handleImageClose() {
      this.drawer = false
      this.previewUrl = []
    },
    handleSend(message, next, file) {
      const { IMUI } = this.$refs
      if (file) {
        // 判断文件如果大于5M就删除该聊天消息
        if (file.size > 5242880) {
          IMUI.removeMessage(message.id)
          return this.$message.error('上传的内容不等大于5MB！')
        }

        uploadFile(file, JSON.stringify(message)).then(res => {
          message.content = res
          IMUI.updateMessage(message)
          next()
          this.$ws.$ws.send(JSON.stringify(message))
        }).catch(() => {
          next({ status: 'failed' })
        })
      } else {
        if (message.toContactId === '4') {
          if (message.type !== 'text') {
            this.$modal.msgWarning('机器人仅支持文本聊天')
            next({ status: 'failed' })
          } else {
            next()
            this.$ws.$ws.send(JSON.stringify(message))
          }
        } else {
          const data = {
            message: JSON.stringify(message)
          }
          addMessage(data).then(() => {
            next()
            this.$ws.$ws.send(JSON.stringify(message))
          }).catch(() => {
            next({ status: 'failed' })
          })
        }
      }
    },
    handleChangeContact(contact, instance) {
      this.$store.dispatch('setCurrentContractId', contact.id)
      const data = this.contactList.find((item) => item.id === contact.id)
      this.$store.dispatch('subUnreadContract', contact)
      if (data.unread !== 0) {
        updateMessagesCheck(contact.id, this.user.id).then((res) => {
          this.$store.dispatch('subUnread', contact.unread)
        })
        instance.updateContact({
          id: contact.id,
          unread: 0
        })
        this.contactList.map((item) => {
          if (item.id === contact.id) {
            item.unread = 0
          }
          return item
        })
      }
      instance.closeDrawer()
    },
    handlePullMessages(contact, next, instance) {
      if (this.currentContactId !== instance.currentContactId) {
        this.pageNumber = 1
        this.currentContactId = instance.currentContactId
      }
      getMessages(this.pageNumber, this.pageSize, this.user.id, instance.currentContactId).then((res) => {
        this.total = res.total
        const row = res.rows
        const messages = []
        for (let i = row.length - 1; i >= 0; i--) {
          const userObj = {
            // 如果 id == this.user.id消息会显示在右侧，否则在左侧
            id: row[i].user.id,
            displayName: row[i].user.nickName,
            avatar: row[i].user.avatar
          }
          const message = {
            id: row[i].id,
            status: row[i].messageStatus === '0' ? 'success' : 'false',
            type: row[i].type,
            sendTime: row[i].createTime,
            content: row[i].message,
            toContactId: row[i].toUserId,
            fileSize: row[i].fileSize,
            fileName: row[i].fileName,
            fromUser: userObj
          }
          messages.push(message)
        }
        let isEnd = false
        if (
          instance.getMessages(instance.currentContactId).length +
          messages.length >=
          this.total
        ) {
          isEnd = true
        } else {
          this.pageNumber++
        }
        next(messages, isEnd)
      })
    },
    download(src, name, type) {
      const a = document.createElement('a')
      if (type === 'image') {
        a.download = name || 'pic'
      } else {
        a.download = name || 'file'
      }
      a.href = src
      a.click()
    }
  }
}
</script>

<style scoped >
  ::selection {
    background: #000;
    color: #fff;
  }

  .imui-center /deep/ .el-icon-circle-close {
    color: #ffffff;
    background: red;
    border-radius: inherit;
  }
  .imui-center /deep/.lemon-message-text .lemon-message__content img{
    width: auto;
  }
  .imui-center /deep/.lemon-editor__emoji-item{
    width: auto;
  }
  body {
    font-family: "Microsoft YaHei";
    background: #f6f6f6 !important;
  }
  .link a {
    display: inline-block;
    margin: 0 5px;
    text-decoration: none;
    background: #ffba00;
    border-radius: 4px;
    padding: 5px 10px;
    color: rgba(0,0,0,0.8);
  }
  .logo {
    position: relative;
    display: inline-block;
    margin: 60px auto;
    user-select: none;
  }
  .logo-text {
    font-size: 38px;
  }
  .logo-sub {
    font-size: 18px;
    color: #999;
    font-weight: 300;
  }
  .logo-badge {
    position: absolute;
    top: -10px;
    left: 230px;
    background: #000;
    border-radius: 16px;
    color: #f9f9f9;
    font-size: 12px;
    padding: 4px 8px;
  }
  .title {
    font-size: 24px;
    line-height: 26px;
    border-left: 1px solid #ffba00;
    padding-left: 15px;
    margin-bottom: 15px;
    margin-top: 30px;
    user-select: none;
  }
  .table {
    width: 100%;
    border-radius: 10px;
    background: #fff;
    border-collapse: collapse;
  }
  .table tr {
    cursor: pointer;
  }
  .table tr:not(.table-head):hover {
    background: #ffba00 !important;
  }
  .table tr:nth-of-type(even) {
    background: #f9f9f9;
  }
  .table th {
    user-select: none;
    color: #999;
  }
  .table td, .table th {
    text-align: left;
    padding: 10px 15px;
    font-size: 14px;
    font-weight: normal;
  }
  .imui-center {
  }
  .imui-center .lemon-drawer {
    border: 1px solid #ddd;
    border-left: 0;
  }
  .drawer-content {
    padding: 15px;
  }
  .more {
    font-size: 12px;
    line-height: 24px;
    height: 24px;
    position: absolute;
    top: 14px;
    right: 14px;
    cursor: pointer;
    user-select: none;
    color: #f1f1f1;
    display: inline-block;
    border-radius: 4px;
    background: #111;
    padding: 0 8px;
  }
  .more:active {
    background: #999;
  }
  .bar {
    text-align: center;
    line-height: 30px;
    background: #fff;
    margin: 15px;
    color: #666;
    user-select: none;
    font-size: 12px;
  }
  .cover {
    text-align: center;
    user-select: none;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
  .cover i {
    font-size: 84px;
    color: #e6e6e6;
  }
  .cover p {
    font-size: 18px;
    color: #ddd;
    line-height: 50px;
  }
  .article-item {
    line-height: 34px;
    cursor: pointer;
  }
  .article-item:hover {
    text-decoration: underline;
    color: #318efd;
  }
  pre {
    background: #fff;
    border-radius: 8px;
    padding: 15px;
  }
  .lemon-simple .lemon-container {
    z-index: 5;
  }
  .lemon-simple .lemon-drawer {
    z-index: 4;
  }
  input#switch[type=checkbox] {
    height: 0;
    width: 0;
    display: none;
  }
  label#switch-label {
    cursor: pointer;
    text-indent: -9999px;
    width: 34px;
    height: 20px;
    background: #aaa;
    display: block;
    border-radius: 100px;
    position: relative;
  }
  label#switch-label:after {
    content: '';
    position: absolute;
    top: 2px;
    left: 2px;
    width: 16px;
    height: 16px;
    background: #fff;
    border-radius: 20px;
    transition: 0.3s;
  }
  input#switch:checked + label {
    background: #0fd547;
  }
  input#switch:checked + label:after {
    left: calc(100% - 2px);
    transform: translateX(-100%);
  }
  label#switch-label:active:after {
    width: 20px;
  }

</style>
